<template>
    <van-address-edit 
        show-delete
        show-set-default
        :area-list="areaList"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        :address-info="address"
        @save="save"
        @delete="del"
    />
</template>

<script setup>
    //引入地区数据
    import { areaList } from '@vant/area-data'
    const {proxy} = getCurrentInstance()
    //传递过来一个id
    // 然后根据id去查询一下，然后把值赋给 address
    let addressId = proxy.$route.query.addressId ? proxy.$route.query.addressId : 0;
    //进入页面后挂载
   
    // console.log(proxy.$route.query.addressId)
    let address = ref({})
    onMounted(()=>{
        Info()
    })
    //定义一个方法 把id给传入过去 点击后的内容显示
    const Info = async ()=>{
        var res = await proxy.$POST({
            url:'/address/info',
            params:{id:addressId,busid:proxy.$business.value.id}
        })
        if(res.code=="0"){
            //找不到返回回去
            proxy.$fail({
                messages:res.msg,
                duration:1000,
                onClose:()=>proxy.$router.go(-1)
            });
            return false
        }
        address.value = {      
            name: res.data.consignee,
            tel: res.data.mobile,
            addressDetail: res.data.address,//详细地址
            areaCode: res.data.district || res.data.city || res.data.province, //必填
            isDefault: res.data.status==1?true:false,
        }
    }
    //修改保存
    const save = async (values) => {
        //修改相当于一种修改的内容
        //封装数据
        let data = {
            id:addressId,
            busid:proxy.$business.value.id,
            code:values.areaCode,
            mobile:values.tel,
            consignee:values.name,
            address:values.addressDetail,
            status:values.isDefault?1:0
        }
        var result = await proxy.$POST({
            url:"/address/edit",
            params:data
        })
        if(result.code=="0"){
            proxy.$fail(result.msg);
            return false
        }
        //成功就跳转
        proxy.$success({
            message:result.msg,
            duration:1000,
            onClose:()=>proxy.$router.go(-1)
        })
    }
    //删除 做一个删除提醒
    const del = async ()=>{
        //删除需要的id
       //做一个confrim提醒框
       proxy.$confirm({
            title:'删除提醒',//提醒的标题
            message:'是否确认删除'//提醒文本
       }).then( async()=>{ //then 就是点击确认删除
        var resDel = await proxy.$POST({
            url:'/address/del',
            params:{id:addressId},
        })
        if(resDel.code=="0"){
            proxy.$fail(resDel.msg);
            return false
        }
        //删除成功后
        proxy.$success({
            message:resDel.msg,
            duration:1000,
            onClose:()=>proxy.$router.go(-1)
        })
       }
       ).catch(()=>console.log('取消删除')//catch取消删除

       )
    }
</script>